//
//  ESUNRefreshView.m
//  TEST
//
//  Created by wang yongfeng on 14-3-20.
//  Copyright (c) 2014年 wang yongfeng. All rights reserved.
//

#import "ESUNRefreshView.h"

@implementation ESUNRefreshView
@synthesize scrollView = _scrollView;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        //320 60
        [self setBackgroundColor:[UIColor clearColor]];
        self.stateLable = [[UILabel alloc] init];
        [self.stateLable setFrame:CGRectMake(0,0,100, 20)];
        [self.stateLable setCenter:CGPointMake(175, 30)];
        self.stateLable.font = [UIFont fontWithName:FONT_NAME size:13];
        self.stateLable.textColor = dESRefreshContentColor;
        self.stateLable.backgroundColor = [UIColor clearColor];
        self.stateLable.textAlignment = NSTextAlignmentCenter;
        [self.stateLable setText:dESRefreshHeaderNormal];
        //指示器
        self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [self.indicator setCenter:CGPointMake(120, 30)];
        [self addSubview:self.stateLable];
        [self addSubview:self.indicator];
        self.canRefresh = YES;
        //默认状态
        _state = eESRefreshStateNormal;
    }
    return self;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
*/

- (void)setScrollView:(UIScrollView *)scrollView
{
    // 移除之前的监听器
    [_scrollView removeObserver:self forKeyPath:dESRefreshContentOffset context:nil];
    // 监听contentOffset
    
    [scrollView addObserver:self forKeyPath:dESRefreshContentOffset options:NSKeyValueObservingOptionNew context:nil];
    // 设置scrollView
    _scrollView = scrollView;
    [_scrollView addSubview:self];
}

//开始刷新
- (void)beginRefreshing
{
    [self setRefreshState:eESRefreshStateRefresh];
}

//结束刷新
- (void)endRefreshing
{
    [self setRefreshState:eESRefreshStateNormal];
}

//获得状态
- (BOOL)isRefreshing
{
    return eESRefreshStateRefresh == _state;
}

//设置状态
- (void)setRefreshState:(ESUNRefreshState)state
{
    _state = state;
}

//释放
- (void)free
{
    [_scrollView removeObserver:self forKeyPath:dESRefreshContentOffset context:nil];
}

@end
